package com.fxcalibre.fxml.control;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageViewBuilder;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;

import com.fxcalibre.fxml.view.FXMLViewLoader;
import com.fxcalibre.syncservices.imdb.ImdbNameSearch;
import com.fxcalibre.syncservices.imdb.parser.NameResult;

public class ImdbSearchNameResult extends VBox
{
	Stage dialogStage;
	@FXML
	ListView<NameResult> listResults;

	String name;
	NameResult selectedNameResult;

	ObservableList<NameResult> data = FXCollections.observableArrayList();

	public ImdbSearchNameResult()
	{
		System.out.println("ImdbSearchNameResult-->");
		FXMLViewLoader.load(this, "ImdbSearchResults.fxml");
		listResults.setItems(data);
		listResults.setCellFactory(new Callback<ListView<NameResult>, ListCell<NameResult>>()
		{
			@Override
			public ListCell<NameResult> call(ListView<NameResult> list)
			{
				return new PersonImdbCell();
			}
		});
		System.out.println("ImdbSearchNameResult<--");
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
		data.clear();
		data.addAll(ImdbNameSearch.search(name));
	}

	public NameResult getSelectedNameResult()
	{
		return selectedNameResult;
	}

	@FXML
	protected void selectAndClose(ActionEvent event)
	{
		selectedNameResult = listResults.getSelectionModel().getSelectedItem();
		dialogStage.close();
	}

	@FXML
	protected void cancel(ActionEvent event)
	{
		dialogStage.close();
	}

	public void showInStage()
	{
		dialogStage = new Stage();
		dialogStage.setTitle("Edit Media");
		dialogStage.initModality(Modality.APPLICATION_MODAL);
		Scene scene = new Scene(this);
		dialogStage.setScene(scene);
		dialogStage.sizeToScene();
		dialogStage.showAndWait();
	}

	static class PersonImdbCell extends ListCell<NameResult>
	{
		@Override
		public void updateItem(NameResult item, boolean empty)
		{

			super.updateItem(item, empty);
			if (item != null)
			{
				HBox hBox = new HBox();
				System.out.println(item.getImgUrl());
				if (item.getImgUrl() != null)
				{
					hBox.getChildren().add(ImageViewBuilder.create().image(new Image(item.getImgUrl())).build());
				}
				hBox.getChildren().add(new Label(item.getName()));
				hBox.getChildren().add(new Label(item.getDescription()));
				setGraphic(hBox);
			}
		}
	}

}
